<template>
  <div class="model-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <ColumnTree
          node-key="id"
          class="columnTree"
          @sendQuotas="getQuotas"
          ref="columnSelect"
          :hasFilter="false"
          :datasourceId="id"
          :showCheckbox="showCheckbox"
          :isDimension="isDimension"
          @dragNode="handleDragNode"
        />
      </el-col>
      <el-col :span="13" :xs="24">
        <el-button type="primary" @click="quotaMode" style="margin-bottom: 10px"
        >预指标关联
        </el-button
        >
        <div class="list">
          <el-table
            :data="tableData"
            border
            class="dimension"
            style="width: 100%"
          >
            <el-table-column label="预指标名称" width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.quota.name }}
              </template>
            </el-table-column>
            <af-table-column label="维度值集合">
              <template slot-scope="scope">
                <el-row
                  v-for="(item, index) in scope.row.dimension"
                  :key="index"
                >
                  <el-tag
                    closable
                    @close="handleClose(item, ele)"
                    style="margin: 5px"
                    v-for="ele in item"
                    :key="ele.id"
                  >{{ ele.dimensionName }}
                  </el-tag
                  >
                  <el-divider v-if="item.length>0"></el-divider>
                </el-row>
              </template>
            </af-table-column>
            <el-table-column align="center" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row.quota.id)"
                >删除
                </el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="5" :xs="24">
        <DimensionTree class="dimensionTree" node-key="id" @sendDimension="getDimension" ref="dimensionSelect"/>
      </el-col>
    </el-row>
    <el-row>
      <el-col style="margin:15px 0" :span="24">
        <div>
          <el-table
            :data="tableData"
            border
            class="dimension"
            style="width: 100%"
          >
            <el-table-column label="预指标名称" width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.quota.name }}
              </template>
            </el-table-column>
            <af-table-column label="维度值集合">
              <template slot-scope="scope">
                <el-row
                  v-for="(item, index) in scope.row.dimension"
                  :key="index"
                >
                  <el-tag
                    closable
                    @close="handleClose(item, ele)"
                    style="margin: 5px"
                    v-for="ele in item"
                    :key="ele.id"
                  >{{ ele.dimensionName }}
                  </el-tag
                  >
                  <el-divider v-if="item.length>0"></el-divider>
                </el-row>
              </template>
            </af-table-column>
            <el-table-column align="center" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row.quota.id)"
                >删除
                </el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div>
          <el-button type="primary" @click="quotaMode" style="margin-bottom: 10px"
          >预指标建模
          </el-button
          >
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import ColumnTree from '@/views/quota/modeling/QuotaTree.vue'
import DimensionTree from '@/views/quota/modeling/DimensionTree.vue'
import { quotaModeling } from '@/api/quota/define/define.js'

export default {
  name: 'MetaTree',
  components: { ColumnTree, DimensionTree },
  data() {
    return {
      tableData: [],
      //默认关联维度
      quotas: [],
      dimension: [],
      props: {
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf'
      },
      id: 110,
      allowDrop: false,
      //树结点是否显示checkbox
      showCheckbox: true,
      isDimension: '1',
      columnSelect: [],
      columnList: [],
      droppedItem: '',
      selectColumn: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        zoneTitle: undefined,
        zoneDescription: undefined,
        createBy: undefined,
        createDate: undefined,
        orderNum: undefined,
        orderField: 'ORDER_NUM',
        order: 'asc'
      }
    }
  },
  methods: {
    //删除指标与维度的关系
    handleDelete(id) {
      this.$confirm('是否要删除该关联?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        let idx = this.tableData.findIndex(item => {
          return item.quota.id === id
        })
        this.tableData.splice(idx, 1)
        this.dimension = []
        this.quotas.splice(idx, 1)
        this.$refs.columnSelect.resetTree()
        this.$refs.dimensionSelect.resetTree()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //指标建模
    quotaMode() {
      var map = {}
      this.tableData.forEach((item) => {
        let dimensionList = []
        item.dimension.forEach((arr) => {
          let flag = true
          arr.forEach((ele) => {
            if (ele.children && ele.children.length > 0) {
              dimensionList.push({
                id: ele.id,
                name: ele.dimensionName
              })
              flag = false
            }
          })
          if (flag) {
            dimensionList.push({
              id: arr[arr.length - 1].id,
              name: arr[arr.length - 1].dimensionName
            })
          }
        })
        map[item.quota.id] = dimensionList
      })
      quotaModeling(map).then((res) => {
        this.$message('预指标建模成功')
        this.tableData = []
        this.dimension = []
        this.quotas = []
        this.$refs.columnSelect.resetTree()
        this.$refs.dimensionSelect.resetTree()
      }).catch(error => {
        this.$message('预指标建模失败')
      })
    },
    //关闭标签
    handleClose(dimension, ele) {
      let idx = dimension.findIndex((item) => {
        return item.id === ele.id
      })
      dimension.splice(idx, 1)
    },
    //获取选择维度
    getDimension(val) {
      if (this.quotas.length === 0) {
        this.$message('请先选择指标')
        return
      }
      let arr = []
      val.forEach((item) => {
        arr.push(item)
      })
      let dimensionArr = this.dimension
      if (dimensionArr.length === 0) {
        this.dimension.push(arr)
      } else {
        let flag = true
        dimensionArr.forEach((item) => {
          if (item.length === arr.length) {
            let same = true
            arr.forEach((ele) => {
              let idx = item.findIndex((newEle) => {
                return ele.id === newEle.id
              })
              if (idx === -1) {
                same = false
              }
            })
            if (same) {
              flag = false
            }
          }
        })
        if (flag) {
          this.dimension.push(arr)
        }
      }
      this.tableData.forEach((item) => {
        item.dimension = this.dimension
      })
    },
    //获取指标
    getQuotas(quotas) {
      if (this.quotas.length > 0) {
        this.$message('请先将已选预指标建模')
        return
      }
      this.quotas = []
      quotas.forEach((item) => {
        this.quotas.push(item)
      })
      this.quotas.forEach((item) => {
        this.$set(this.tableData, this.tableData.length, {
          quota: item,
          dimension: []
        })
      })
    },
    //懒加载树
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: 'region' }])
      }
      if (node.level > 1) return resolve([])

      setTimeout(() => {
        const data = [
          {
            name: 'leaf',
            leaf: true
          },
          {
            name: 'zone'
          }
        ]

        resolve(data)
      }, 500)
    },
    drop(event) {
      // 判断drop的来源是否为树，与表头的drag/drop事件做区分
      if (this.selectColumn) {
        this.columnList.push(this.selectColumn)
        this.selectColumn = undefined
      }
    },
    handleDragNode(data) {
      this.selectColumn = data
    },
    //穿梭框事件
    // 切换模式 现有树形穿梭框模式transfer 和通讯录模式addressList
    changeMode() {
      if (this.mode == 'transfer') {
        this.mode = 'addressList'
      } else {
        this.mode = 'transfer'
      }
    },
    // 监听穿梭框组件添加
    add(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
      console.log('fromData:', fromData)
      console.log('toData:', toData)
      console.log('obj:', obj)
    },
    // 监听穿梭框组件移除
    remove(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
      console.log('fromData:', fromData)
      console.log('toData:', toData)
      console.log('obj:', obj)
    }
  }
}
</script>

<style lang="less">
.el-scrollbar .el-scrollbar__wrap {
  overflow-x: hidden;
}

.model-container {
  .dimensionTree {
    border: 1px solid #E6EBF5;
  }

  margin: 15px;

  .columnTree {
    border: 1px solid #E6EBF5;
  }
}

.dimension {
  th {
    text-align: center;
  }

  .cell {
    padding: 0;
  }

  .el-table_1_column_2 {
    white-space:nowrap .el-row {
      padding: 10px;
    }
  }
}

.columnTree {
  overflow: auto;

  .el-tree {
    .el-tree-node__content {
      display: inline-block;
      min-width: 100%;
    }

    .el-tree-node__children {
      overflow: visible !important;
    }
  }
}
</style>
